Reference: CCP_L01_B01_Number Guessing Game
🔹 Introduction
The Number
Guessing Game in C is a great project for beginners who want to improve their C programming skills
while having fun! This simple yet engaging game allows users to guess a
randomly generated number while receiving hints to guide them. It also tracks
the best score using file handling,
making it a great project for learning
fundamental C concepts.
In this blog post, we’ll cover:
 ✔️ Game
features & enhancements
 ✔️ Step-by-step implementation
 ✔️ Full C code with explanations
 ✔️ How to run it in Code::Blocks
🔹 Features of the
Game
✅
Random Number
Generation (rand())
 ✅ User Input & Feedback (Too High / Too Low)
 ✅ Attempt Tracking (Stores best score using file
handling)
 ✅ Menu-Driven Interface
 ✅ Statistics Viewing & Reset Option
🔹 Step-by-Step
Implementation
1️⃣ Setting Up the Project
●    
Open Code::Blocks IDE.
●    
Create a new C source file and save it as number_guessing_game.c.
●    
Copy and paste the provided C code (included below).
2️⃣ Understanding the Code Structure
●    
Menu System: Lets users play, view stats, reset stats, or exit.
●    
Game Logic: Generates a random number and takes guesses until the user wins.
●    
File Handling: Stores the best score in a text file (game_stats.txt).
🔹 Full C Code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define FILE_NAME "game_stats.txt"
void displayMenu();
void playGame();
void viewStatistics();
void resetStatistics();
void saveStatistics(int attempts);
int getBestScore();
int main() {
    int
choice;
    do {
       
displayMenu();
       
printf("Enter your choice: ");
       
scanf("%d", &choice);
       
switch (choice) {
           
case 1:
               
playGame();
               
break;
           
case 2:
               
viewStatistics();
               
break;
           
case 3:
               
resetStatistics();
               
break;
           
case 4:
               
printf("Exiting the game. Goodbye!\n");
               
break;
           
default:
               
printf("Invalid choice. Please try again.\n");
       
}
    }
while (choice != 4);
   
return 0;
}
void displayMenu() {
   
printf("\n===== Number Guessing Game =====\n");
   
printf("1. Start New Game\n");
   
printf("2. View Game Statistics\n");
   
printf("3. Reset Statistics\n");
   
printf("4. Exit\n");
   
printf("================================\n");
}
void playGame() {
    int
number, guess, attempts = 0;
   
srand(time(NULL));
   
number = (rand() % 100) + 1;
   
printf("\nI have selected a number between 1 and 100. Try to guess
it!\n");
    do {
       
printf("Enter your guess: ");
       
scanf("%d", &guess);
       
attempts++;
       
if (guess > number) {
           
printf("Too high! Try again.\n");
       
} else if (guess < number) {
           
printf("Too low! Try again.\n");
       
} else {
           
printf("Congratulations! You guessed the correct number in %d
attempts.\n", attempts);
           
saveStatistics(attempts);
       
}
    }
while (guess != number);
}
void viewStatistics() {
    int
bestScore = getBestScore();
   
printf("\n===== Game Statistics =====\n");
    if
(bestScore == 0) {
       
printf("No previous games played yet.\n");
    }
else {
       
printf("Best Score (Least Attempts): %d\n", bestScore);
    }
   
printf("===========================\n");
}
void resetStatistics() {
    FILE
*file = fopen(FILE_NAME, "w");
    if
(file != NULL) {
       
fprintf(file, "0\n");
       
fclose(file);
       
printf("Game statistics reset successfully!\n");
    }
else {
       
printf("Error resetting statistics.\n");
    }
}
void saveStatistics(int attempts) {
    int
bestScore = getBestScore();
    if
(bestScore == 0 || attempts < bestScore) {
       
FILE *file = fopen(FILE_NAME, "w");
       
if (file != NULL) {
           
fprintf(file, "%d\n", attempts);
           
fclose(file);
           
printf("New Best Score! Saved successfully.\n");
       
} else {
           
printf("Error saving game statistics.\n");
       
}
    }
}
int getBestScore() {
    FILE
*file = fopen(FILE_NAME, "r");
    int
bestScore = 0;
    if
(file != NULL) {
       
fscanf(file, "%d", &bestScore);
       
fclose(file);
    }
   
return bestScore;
}
🔹 How to Run the
Game in Code::Blocks
1️⃣ Install Code::Blocks IDE with MinGW Compiler.
 2️⃣ Open Code::Blocks and create a new C source file.
 3️⃣ Paste the above code and Save as number_guessing_game.c.
 4️⃣ Click Build → Build and
Run (F9).
 5️⃣ Play the game in the console window.
🔹 Enhancements
& Future Improvements
🚀 Difficulty Levels (Easy, Medium, Hard)
 ðŸš€ Multiplayer Mode (Two players take turns)
 ðŸš€ Timer-Based Challenge
 ðŸš€ Graphical UI (Using graphics.h)
 ðŸš€ Auto-generated hints (Divisibility, Prime
Number Check)
🔹 Conclusion
The Number
Guessing Game in C is a fantastic project for beginners. It covers C
fundamentals like loops, conditions,
functions, file handling, and user interaction. You can expand it by adding difficulty levels, multiplayer
modes, or even a GUI!
💡 What would you like to add to this game? Let us know in the comments!
🔹 More Resources
📌 Learn C Programming: GeeksforGeeks - C Basics
 ðŸ“Œ Practice More C Projects: GitHub C Projects
👉 Don’t forget to share this post if you found it useful! 🚀
📌 Download Full Code & More C Projects
Below In the eBook link! 👇
------------------------ 
Brief About “C Code Projects for Beginner Students (Ages
8-16)" eBook
Are you a school student aged 8 to 16
with a budding interest in programming, or perhaps looking for a hands-on way
to master C language for your academic projects? Look no further! I am thrilled
to announce the launch of "C Code Projects for Beginner Students,"
your ultimate guide to practical C programming.
Ready to start your coding adventure?
[Click below any links to get your copy of
"C Code Projects for Beginner Students (Ages 8-16)"!] 
eBook CCP_L01 Link: 
https://play.google.com/store/books/details?id=KS54EQAAQBAJ  [Google Play Store]
https://books.google.co.in/books?id=KS54EQAAQBAJ   [Google Books]
Enjoy this eBook CCP_L01 on ‘C Code Projects
for Beginner Students’ series and do not forget to explore other resources
related to this series eBook. Thanks for visiting my blog. 
EBOOK CCP_L01 promotion Blog Link: 
https://myspacemywork2024.blogspot.com/2025/08/unlock-world-of-code-introducing-c-code.html
Happy Reading!
No comments:
Post a Comment